<template>
  <div class="guide-container">
    <!-- 搜索和标题区域 -->
    <div class="search-section">
      <!-- <h2 class="page-title">就医指南</h2> -->
      <div class="search-box">
        <input 
          type="text" 
          placeholder="输入病症关键词或城市名称..." 
          v-model="searchText"
          @input="filterGuides"
        >
        <div class="search-icon">🔍</div>
      </div>
    </div>

    <!-- 指南分类标签 -->
    <div class="tag-section">
      <div 
        v-for="tag in filterTags" 
        :key="tag" 
        class="tag-item"
        :class="{ active: activeTag === tag }"
        @click="selectTag(tag)"
      >
        {{ tag }}
      </div>
    </div>

    <!-- 指南内容区域 -->
    <div class="guide-content">
      <div v-if="filteredGuides.length === 0" class="empty-tip">
        未找到相关指南，请尝试其他关键词
      </div>
      
      <div 
        v-for="(guide, index) in filteredGuides" 
        :key="index" 
        class="guide-card"
        @click="toggleExpand(index)"
      >
        <div class="card-header">
          <div class="step-icon">{{ guide.stepIcon }}</div>
          <h3>{{ guide.title }}</h3>
          <div class="expand-icon">{{ guide.expanded ? '−' : '+' }}</div>
        </div>
        
        <div class="card-content" :class="{ expanded: guide.expanded }">
          <!-- 列表型内容 -->
          <ul v-if="guide.contentType === 'list'">
            <li v-for="(item, i) in guide.content" :key="i">{{ item }}</li>
          </ul>
          
          <!-- 提示型内容 -->
          <div v-if="guide.contentType === 'tip'" class="tip-box">
            <div class="tip-icon">💡</div>
            <p>{{ guide.content }}</p>
          </div>
          
          <!-- 图文型内容 -->
          <div v-if="guide.contentType === 'image'" class="image-guide">
            <img 
              :src="guide.image" 
              alt="就医指南图示" 
              mode="widthFix" 
              @click="previewImage(guide.image)"
              class="preview-image"
            />
            <p>{{ guide.content }}</p>
          </div>
          
          <!-- 紧急联系人 -->
          <div v-if="guide.contentType === 'contacts'" class="contacts-box">
            <a 
              v-for="(contact, ci) in guide.content" 
              :key="ci" 
              :href="`tel:${contact.phone}`"
              class="contact-item"
            >
              <div class="contact-icon">📞</div>
              <div>
                <div class="contact-name">{{ contact.name }}</div>
                <div class="contact-phone">{{ contact.phone }}</div>
              </div>
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="action-bar">
      <button class="action-btn download-btn" @click="addToMemo">加入备忘录</button>
      <button class="action-btn view-btn" @click="showMemoList">查看备忘录</button>
    </div>

    <!-- 备忘录列表弹窗 -->
    <div class="memo-popup" v-if="showMemoPopup">
      <div class="popup-mask" @click="closeMemoList"></div>
      <div class="popup-content">
        <div class="popup-header">
          <text class="popup-title">我的备忘录</text>
          <text class="close-btn" @click="closeMemoList">×</text>
        </div>
        <scroll-view class="memo-list" scroll-y>
          <div v-if="memos.length === 0" class="empty-memo">
            暂无备忘录
          </div>
          <div v-else>
            <div 
              v-for="(memo, index) in memos" 
              :key="memo.id"
              class="memo-item"
              @touchstart="touchStart($event, index)"
              @touchmove="touchMove($event, index)"
              @touchend="touchEnd(index)"
            >
              <div 
                class="memo-content" 
                :style="{ transform: `translateX(${memo.offsetX}px)` }"
                @click="showMemoDetail(memo)"
              >
                <div class="memo-title">{{ memo.content.split('\n')[0] }}</div>
                <div class="memo-time">{{ memo.createTime }}</div>
              </div>
              <div class="delete-btn" @click="deleteMemo(index)">删除</div>
            </div>
          </div>
        </scroll-view>
      </div>
    </div>

    <!-- 备忘录详情弹窗 -->
    <div class="memo-detail-popup" v-if="showDetailPopup">
      <div class="popup-mask" @click="closeMemoDetail"></div>
      <div class="detail-content">
        <div class="detail-header">
          <text class="detail-title">备忘录详情</text>
          <text class="close-btn" @click="closeMemoDetail">×</text>
        </div>
        <scroll-view class="detail-body" scroll-y>
          <div class="detail-text">{{ currentMemo.content }}</div>
          <div class="detail-time">创建时间：{{ currentMemo.createTime }}</div>
        </scroll-view>
      </div>
    </div>
  </div>
</template>

<script>
import guideData from '@/utils/guide.js';

export default {
  name: 'GuidePage',
  data() {
    return {
      guides: guideData, // 导入静态数据
      filteredGuides: guideData, // 初始显示全部数据
      searchText: '',
      activeTag: '全部', // 当前选中的标签
      filterTags: ['全部', '就诊前', '就诊中', '就诊后', '医保', '紧急情况'],
      memos: [], // 存储备忘录列表
      showMemoPopup: false, // 控制弹窗显示
      showDetailPopup: false, // 控制详情弹窗显示
      currentMemo: null, // 当前查看的备忘录
      startX: 0, // 触摸开始位置
      currentIndex: -1 // 当前操作的备忘录索引
    };
  },
  onShow() {
    // 页面显示时加载备忘录
    this.loadMemos();
  },
  // 监听用户点击右上角菜单的「转发」按钮时触发的事件
  onShareAppMessage() {
    return {
      title: '就医指南 - 让就医更轻松',
      path: '/pages/index/guide',
      imageUrl: 'https://img.chinasongzhuang.cn/uploadimg/image/20200219/20200219180104_83804.jpg',
      success: () => {
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail: () => {
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        });
      }
    }
  },
  // 监听用户点击右上角菜单的「分享到朋友圈」按钮时触发的事件
  onShareTimeline() {
    return {
      title: '就医指南 - 让就医更轻松',
      query: 'from=pyq',
      imageUrl: 'https://img.chinasongzhuang.cn/uploadimg/image/20200219/20200219180104_83804.jpg'
    }
  },
  methods: {
    // 搜索过滤指南内容
    filterGuides() {
      if (!this.searchText.trim()) {
        this.filteredGuides = this.guides;
        return;
      }
      
      const searchLower = this.searchText.toLowerCase();
      this.filteredGuides = this.guides.filter(guide => {
        const inTitle = guide.title.toLowerCase().includes(searchLower);
        const inContent = JSON.stringify(guide.content).toLowerCase().includes(searchLower);
        return inTitle || inContent;
      });
    },
    
    // 选择分类标签
    selectTag(tag) {
      this.activeTag = tag;
      if (tag === '全部') {
        this.filteredGuides = this.guides;
      } else {
        this.filteredGuides = this.guides.filter(
          guide => guide.tags.includes(tag)
        );
      }
    },
    
    // 展开/收起卡片
    toggleExpand(index) {
      this.filteredGuides[index].expanded = !this.filteredGuides[index].expanded;
      // 手动触发Vue的更新
      this.filteredGuides = [...this.filteredGuides];
    },
    
    // 加入备忘录
    addToMemo() {
      // 获取当前展开的指南内容
      const expandedGuides = this.filteredGuides.filter(guide => guide.expanded);
      if (expandedGuides.length === 0) {
        uni.showToast({
          title: '请先展开需要备忘的内容',
          icon: 'none'
        });
        return;
      }

      // 生成备忘录内容
      let memoContent = '就医指南备忘录\n\n';
      expandedGuides.forEach(guide => {
        memoContent += `${guide.title}\n`;
        if (guide.contentType === 'list') {
          guide.content.forEach(item => {
            memoContent += `- ${item}\n`;
          });
        } else {
          memoContent += `${guide.content}\n`;
        }
        memoContent += '\n';
      });

      // 保存到本地存储
      try {
        const memos = uni.getStorageSync('memos') || [];
        memos.push({
          content: memoContent,
          createTime: new Date().toLocaleString(),
          id: Date.now()
        });
        uni.setStorageSync('memos', memos);
        
        uni.showToast({
          title: '已加入备忘录',
          icon: 'success'
        });
      } catch (e) {
        console.error('保存失败：', e);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      }
    },

    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: url,
        indicator: 'number',
        loop: false,
        success: () => {
          console.log('预览图片成功');
        },
        fail: (err) => {
          console.error('预览图片失败：', err);
          uni.showToast({
            title: '预览图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 加载备忘录
    loadMemos() {
      try {
        const memos = uni.getStorageSync('memos') || [];
        // 为每个备忘录添加偏移量属性
        this.memos = memos.map(memo => ({
          ...memo,
          offsetX: 0
        }));
      } catch (e) {
        console.error('加载备忘录失败：', e);
      }
    },

    // 显示备忘录列表
    showMemoList() {
      this.loadMemos(); // 重新加载备忘录
      this.showMemoPopup = true;
    },

    // 关闭备忘录列表
    closeMemoList() {
      this.showMemoPopup = false;
      // 重置所有备忘录的偏移量
      this.memos.forEach(memo => {
        memo.offsetX = 0;
      });
    },

    // 触摸开始
    touchStart(e, index) {
      this.startX = e.touches[0].clientX;
      this.currentIndex = index;
    },

    // 触摸移动
    touchMove(e, index) {
      if (this.currentIndex !== index) return;
      
      const moveX = e.touches[0].clientX - this.startX;
      // 限制只能向左滑动，且最大滑动距离为删除按钮的宽度
      const offsetX = Math.min(0, Math.max(-80, moveX));
      this.memos[index].offsetX = offsetX;
    },

    // 触摸结束
    touchEnd(index) {
      if (this.currentIndex !== index) return;
      
      const offsetX = this.memos[index].offsetX;
      // 如果滑动距离超过删除按钮宽度的一半，则自动展开
      if (offsetX < -40) {
        this.memos[index].offsetX = -80;
      } else {
        this.memos[index].offsetX = 0;
      }
      this.currentIndex = -1;
    },

    // 删除备忘录
    deleteMemo(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条备忘录吗？',
        success: (res) => {
          if (res.confirm) {
            try {
              const memos = uni.getStorageSync('memos') || [];
              memos.splice(index, 1);
              uni.setStorageSync('memos', memos);
              this.memos = memos.map(memo => ({
                ...memo,
                offsetX: 0
              }));
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } catch (e) {
              console.error('删除失败：', e);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },

    // 显示备忘录详情
    showMemoDetail(memo) {
      // 如果正在左滑，不显示详情
      if (this.currentIndex !== -1) return;
      this.currentMemo = memo;
      this.showDetailPopup = true;
    },

    // 关闭备忘录详情
    closeMemoDetail() {
      this.showDetailPopup = false;
      this.currentMemo = null;
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
.guide-container {
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.search-section {
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  margin-bottom: 15px;
  color: #2c3e50;
  font-weight: bold;
}

.search-box {
  display: flex;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.search-box input {
  flex: 1;
  padding: 12px 15px;
  border: none;
  outline: none;
  font-size: 16px;
}

.search-icon {
  padding: 12px 15px;
  background: #f5f7fa;
  font-size: 18px;
}

.tag-section {
  display: flex;
  overflow-x: auto;
  margin-bottom: 15px;
  padding-bottom: 5px;
}

.tag-item {
  padding: 8px 15px;
  background: #f0f4f8;
  border-radius: 16px;
  margin-right: 10px;
  font-size: 14px;
  white-space: nowrap;
  color: #5a84b4;
  cursor: pointer;
}

.tag-item.active {
  background: #409eff;
  color: white;
  font-weight: bold;
}

.guide-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px;
  cursor: pointer;
  background: #fafbfc;
  border-bottom: 1px solid #eee;
}

.step-icon {
  font-size: 24px;
  margin-right: 12px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #ecf5ff;
  color: #409eff;
}

.card-header h3 {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
  color: #333;
}

.expand-icon {
  font-size: 20px;
  font-weight: bold;
  color: #999;
}

.card-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.card-content.expanded {
  max-height: 1000px;
  padding: 15px;
}

ul {
  padding-left: 20px;
  margin: 0;
}

ul li {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #555;
}

.tip-box {
  background: #f8fafc;
  border-left: 3px solid #67c23a;
  padding: 12px;
  display: flex;
}

.tip-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #67c23a;
}

.tip-box p {
  margin: 0;
  line-height: 1.6;
}

.image-guide {
  text-align: center;
  padding: 10px;
}

.image-guide img {
  width: 100%;
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-guide p {
  color: #666;
  line-height: 1.6;
  margin: 0;
  padding: 0 10px;
}

.contacts-box {
  display: flex;
  flex-direction: column;
}

.contact-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  color: inherit;
  text-decoration: none;
}

.contact-item:last-child {
  border-bottom: none;
}

.contact-icon {
  font-size: 24px;
  margin-right: 12px;
  color: #409eff;
}

.contact-name {
  font-weight: bold;
  color: #333;
}

.contact-phone {
  color: #666;
  font-size: 15px;
}

.action-bar {
  position: sticky;
  bottom: 20px;
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding: 0 16px;
}

.action-btn {
  width: 45%;
  padding: 14px 0;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s;
}

.download-btn {
  background: #409eff;
  color: white;
}

.view-btn {
  background: #67c23a;
  color: white;
}

.download-btn:active,
.view-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

/* 备忘录弹窗样式 */
.memo-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;
  max-height: 70vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 24px;
  color: #999;
  padding: 0 10px;
}

.memo-list {
  max-height: calc(70vh - 60px);
}

.memo-item {
  position: relative;
  margin-bottom: 12px;
  overflow: hidden;
}

.memo-content {
  position: relative;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  transition: transform 0.3s ease;
  z-index: 1;
}

.delete-btn {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 80px;
  background: #ff4d4f;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.memo-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.memo-time {
  font-size: 12px;
  color: #999;
}

.empty-memo {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

.preview-image {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.preview-image:active {
  transform: scale(0.98);
}

/* 备忘录详情弹窗样式 */
.memo-detail-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.detail-content {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 600px;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  max-height: 80vh;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.detail-body {
  max-height: calc(80vh - 80px);
}

.detail-text {
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

.detail-time {
  margin-top: 20px;
  font-size: 14px;
  color: #999;
  text-align: right;
}

.memo-content {
  cursor: pointer;
}

.memo-content:active {
  opacity: 0.8;
}
</style> 